#!usr/bin/python
# -*- coding:utf-8 -*-
#Copyright 2020 labsight
import pkgutil
import sys
from base.pyLog import PyLog


class PyPlugin(object):
    def __init__(self):
        pass

    @staticmethod
    def dyclass(package,module=None,baseclass=None,errexit=True):
        try:
            if not module:
                module = package[package.rfind(".")+1:]
                module = module[:1].upper()+module[1:]
            try:
                pack = __import__(package,fromlist=[module])
            except Exception as e:
                if not errexit:
                    PyLog("agt").warn(e)
                    return None
                else:
                    PyLog("agt").err(e)
            myclass = getattr(pack,module)
            if baseclass and issubclass(myclass,baseclass):
                return myclass
            return myclass if not  baseclass else None
        except Exception as e:
            PyLog("agt").err(e,sysexit=errexit)

    def getModule(self,package,module=None,baseclass=None):
        """
        :param package: edeploy.edyunderlaystartrunn.sunnBase
        :param module: if module+None,get module from package.last,means:SunBase
        :return:
        """
        return AgtPlugin.dyclass(package,module,baseclass)

    @staticmethod
    def tryImport(package,module=None):
        try:
            if not module:
                module = package[package.rfind(".")+1:]
                module = module[:1].upper()+ module[1:]
            mypack = __import__(package,fromlist=[module])
            return mypack
        except Exception as e:
            pass

    def tryGet(self,packobj,module=None,baseclass=None):
        try:
            if not module:
                package = packobj.__name__
                module = package[package.rfind(".")+1:]
                module = module[:1].upper()+module[1:]
            myclass = getattr(packobj,module)
            if baseclass and issubclass(myclass,baseclass):
                return myclass
            return myclass if not baseclass else None
        except Exception as e:
            HitLog("agt").err(e)

    @staticmethod
    def iterModules(package,prefix=''):
        try:
            pk = __import__(package,globals(),locals(),[''],0)
            for filefiner,name,ispkg in pkgutil.iter_modules(pk.__path__,prefix):
                yield filefiner,name,ispkg
        except Exception as e:
            HitLog("agt").err(e)

    @staticmethod
    def walkPackage(package,prefix=''):
        try:
            pk=__import__(package,globals(),locals(),[''],0)
            for item in pkgutil.walk_packages(pk.__path__,prefix):
                if sys.version_info.major == 2 or sys.version_info.major==3 and sys.version_info.minor==5:
                    yield (item[1],item[2])
                else:
                    yield (item.name,item.ispkg)
        except Exception as e:
            HitLog("agt").err(e)

    @staticmethod
    def deepPackage(package,prefix=''):
        packs = []

        def __dep__(package,packs,prefix):
            for packname,ispack in AgtPlugin.walkPackage(package,prefix):
                ''''兼容python2和python3的数据差异结构'''
            if ispack:
                __dep__(package+"."+packname,packs,prefix)
            else:
                packs.append("%s.%s" % (package,packname))
        __dep__(package,packs,prefix)
        return packs